box_log("leadingtv");
if(typeof $ == "undefined"){
    var $ = function (id) {
        if(typeof id != "string") return null;
        return document.getElementById(id);
    }
}

//模板
(function(){
    var cache = {};

    this.tmpl =  function (str, data){

        if(!/\W/.test(str)){
            var fn = cache[str] = cache[str]||tmpl(document.getElementById(str).innerHTML);
        }else{
            var html = str
                .replace(/\r/g, " ")
                .replace(/\n/g, " ")
                .replace(/  /g, " ")
                .split("name=\"").join("id=\"leadingtv_{{i}}_")
                .split("<%").join("~")
                .replace(/((^|%>)[^\x09]*)'/g, "$1~")
                .split("{{").join("',")
                .split("}}").join(",'")
                .split("~").join("');")
                .split("%>").join("p.push('")
                .split("~").join("\\'");
            //茁壮高清盒子 正则匹配有bug 匹配后面的符号 而不是匹配第一个符号
            //html = html.replace(/#=(.*?)%>/g, "',$1,'");
            // html = html.split("#=").join("',");
            // html = html.split("=#").join(",'");
            // html = html.split("#").join("');");
            // html = html.split("%>").join("p.push('");
            // html = html.split("#").join("\\'");

            var fnScript =  "var p=[];" + "p.push('" + html+"');return p.join('');"
            var fn =  new Function("data",fnScript );
        }

        return data ? fn( data ) : fn;
    };
})();

function FocusTables(obj) {

    this.beforeCreate();
    this._obj = obj;
    var that = this;
    for (var i in this._obj){
        this[i] = this._obj[i];
    }

    if(this.name == "page" || !this.name ){
        this.parentDom = document.body;
        this.grabEvent = function(_event){

            var code = keyEvent(_event);
            switch(code){
                case "KEY_UP": //
                    that.focusMove("up");
                    return false;
                    break;
                case "KEY_DOWN": //
                    that.focusMove("down");
                    return false;
                    break;
                case "KEY_LEFT": //
                    that.focusMove("left");
                    return false;
                    break;
                case "KEY_RIGHT": //
                    that.focusMove("right");
                    return false;
                    break;
                case "KEY_SELECT": //
                    that.doSelect();
                    return false;
                    break;
                case "KEY_EXIT":
                case "KEY_BACK":
                    that.doBack(that.select_item);
                    return false;
                    break;
                case 22201://认证成功
                    GlobalVarManager.setItemStr("vodNavCheck","true");
                    that.navCheckSuccess();
                    return false;
                    break;
                case 22202://认证失败
                    //GlobalVarManager.setItemStr("vodNavCheck","false");
                    that.navCheckError();
                    return false;
                    break;
                case 5969://在第一次画图时才通知底层页面分辨率，可能比init中创建播放器时间晚，会导致从标清切到portal小视频位置不对，因此这里收到此消息后再创建播放器并播放视频
                    that.createMediaPlayer();
                    return 0;
                    break;
                case 5202:										// open success
                case 13001:
                    that.playVideoStart();
                    return 0;
                    break;
                case "IPANEL_PLAY_END":
                    that.playVideoEnd();
                    return 0;
                    break;
                default:
                    break;
            }
        };
        this.init();
    }

}

FocusTables.prototype = {
    index:0,//焦点index
    pos:0,
    select_index:0,//选中index
    page:0,
    total_page:0,
    create:function(){
        console.log(this.name+"life","created")
    },
    beforeCreate:function(){
        
    },
    updated:function(){
        
    },
    beforeUpdate:function(call){
        
    },
    //只有首次创建会执行
    init : function() {

        this.__proto__.constructor = FocusTables;
        if(typeof this.containner == "undefined" || !this.containner){

            var containner = document.createElement("div");
            containner.style.position="absolute";
            containner.style.left = (this.left||0) + "px";
            containner.style.top = (this.top||0) + "px";
            containner.style.width = (this.width||1280) +"px";
            containner.style.height = (this.height||720) + "px";
            // containner.style.overflow = "hidden";
            containner.id = this.name+"-containner";
            containner.name = this.name;
            this.containner = containner;
            this.parentDom.appendChild(this.containner);
        }

        var dom = document.createElement("div");
        dom.id = this.name+"-dom";
        domStyle({
            "position":"absolute",
            "left":0,
            "top":0
        },dom);
        dom.style.width = "100%";
        dom.style.height = "100%";
        if(typeof this.background!="undefined"){
            if(this.background.indexOf("#")!=-1 || this.background.indexOf("rgba")!=-1){
                dom.style.background = this.background;
            }else{
                dom.style.background = "url("+this.background+")";
            }
        }
        this.dom = dom;

        this.containner.appendChild(this.dom);
        if(typeof this.data != "undefined" ){
            this.setData(this.data);
        }else{
            console.log("data 不合法");
        }

        this.create();

    },
//这里是对data进行处理  初始化 生成data等等操作
    //第一次init 90%是空的数组
    setData:function(data){
        if(data instanceof Array!=true){
            this.data = [];
        }
        this.initData(data);

        this.select_item = this.data[this.index];
        //这里是初始化位置宽高
        this.render();
    },
    initData:function(data){
        this.data = data||[];
        if(this.data.length == 0 ){
            this.disabled = true;
        }else{
            this.disabled = false;
        }
        if(this.templateData || this.listItem||this.name == "page"){
            var newData = produceTemplateArr(this.data,this.templateData,this.listItem);
            this.data = newData;
        }

    },
    render:function(){
        this.beforeUpdate();
        //渲染模板后添加到dom里面去

        if(this.dom){

            if(this.name != "page" && typeof this.name != "undefined"){
                this.dom.innerHTML = "";
                //这里会替换掉原来的dom
                //这里有个问题  替换掉了原来的tmplate;

                this.dom.innerHTML = this.template(this);
                this.select_item = this.data[0];

            }

            if(this.data.length>0){

                var focusItem;
                var focusTables = this.data;
                for(var i = 0 ,len = focusTables.length; i <len;i++){

                    focusItem = focusTables[i];

                    if(!(focusItem instanceof FocusTables && focusItem.data)){

                        focusItem.downObj = null;
                        focusItem.upObj = null;
                        focusItem.leftObj = null;
                        focusItem.rightObj = null;
                        focusItem.dom = $("leadingtv_"+focusItem.index+"_"+this.name);

                    }else{
                        focusItem.parentDom = this.dom;
                        focusItem.containner = null;
                        focusItem.dom = null;
                        focusItem.init();
                    }

                }
            }
            this.updated()
        }





    },
    template:function(obj){

        if(obj.tpl){
            var str = tmpl(obj.tpl);
            //第二次复用  这么做的话 模板变化就无效了  所以 模板变化必须要重置一下
            this.template = str;
            return str(obj);
        }


    },
    setTpl:function(tpl){
        this.tpl = tpl;
        this.template = function(obj){
            //这里应该用this
            var str = tmpl(this.tpl);
            //第二次复用  这么做的话 模板变化就无效了  所以 模板变化必须要重置一下
            //解析完成 变成renden函数了 下次调用直接解析HTML 无需生成函数
            this.template = str;
            //再传入数据 返回HTML
            return str(obj);
        }
    },

    searchShortPath:function(_derection){
        if(!(this.data instanceof Array)){
            console.error("data must be Array");
            return;
        }

        var selectItem = this.select_item;
        var focusTables = this.data;
        var len = focusTables.length-1;
        var focusItem = null;
        var candidate = null;

        //todo 支持多维数组的创建 以子作为候选者 父不参与
        for(var i = len ; i >=0;i-- ){
            focusItem = focusTables[i];
            //判断是否在某个方向上
            var isInDerection2 = isInBeamDerection(_derection,focusItem,selectItem);
            //2 不在方向上
            if(!isInDerection2){
                //console.log("不在方向上的item:"+focusItem.title);
                continue;
            }

            if(focusItem instanceof FocusTables && focusItem.data.length == 0){

                continue;

            }

            if(focusItem["disabled"]){
                //console.log("被禁用的item:"+focusItem.title);
                continue;
            }
            //比较候选人
            candidate = isBetterCandidate(_derection,candidate,focusItem,selectItem)?focusItem:candidate;
        }
        return candidate;
    },

    focusMove:function(_derection){


        var derectionObj = {
            'left':'right',
            'right':'left',
            'up':'down',
            'down':'up'
        };


        
        var item ;
        var select_item = this.select_item;
	    console.log(this.select_item);
        if((select_item instanceof FocusTables && select_item.data)){

            //这里截取了上层的移动事件 把它转移给了下层的对象
            var next_item = select_item.focusMove(_derection);

            //如果是没找到 就应该返回了
            if(next_item != "nofound"){
                return;
            }
        }
	 
        //寻找算法
        item = this.searchShortPath(_derection);
        //item = select_item[_derection+"Obj"]!="nofound"&&select_item[_derection+"Obj"]&&!select_item[_derection+"Obj"]["disabled"]?select_item[_derection+"Obj"]:this.searchShortPath(_derection,500);
        // if(item&&item.disabled == true){
        //     item = this.searchShortPath(_derection);
        // }

        if(typeof item == "undefined" || item == null ){

            item = "nofound";
        }

        if(typeof item.data != "undefined"&&item.data.length==0 ){

            item = "nofound";
        }

        //如果焦点的data为空不应该获得焦点的
        if(typeof item != "undefined" && item !== "nofound"  && item !=null){
            if(!item.dom){
                item.dom = $("leadingtv_"+item.index+"_"+this.name);
            }
            var lastItem = this.select_item;
            item[derectionObj[_derection]+"Obj"] = this.select_item;
            this.index = item.index;
            this.pos = item.index;
            this.select_item = item;
            this.focusChange(item,lastItem);
            if(lastItem&&typeof lastItem.data !="undefined"){
                lastItem.itemLoseFocus();
            }
            if(typeof item.data != "undefined"&&item.data.length>0  ){
                this.itemLoseFocus();
                item.itemGetFocus();
            }
        }

        //对当前焦点的某个方向赋值  下次无需再进行搜索
        if(typeof select_item[_derection+"Obj"] == "undefined" && item !=null){
            if(!(item instanceof FocusTables)||!item.data){
                select_item[_derection+"Obj"] = item;
            }
        }

        if(!item || item === "nofound"){
            this.overSize(_derection);
        }
        return item;
    },

    setSelectIndex:function(index){
        var ii  = parseInt(index) == index?parseInt(index):0;
        this.select_index = ii;
        this.selectIndexChange(ii);
    },
    getSelectIndex: function(){
        return this.select_index;
    },
    selectIndexChange:function(ii){
        console.log("select index change:"+ii);
    },
    setSelectItem:function(i){
        var ii = parseInt(i);

        if( ii == ii){
            if(typeof this.data[ii] == "undefined"){
                return;
            }
        }else{
            ii = 0;
        }
        this.select_index = ii;
        this.select_item = this.data[ii];
    },
    getSelectItem: function(i){
        var ii = parseInt(i);

        if( ii !== ii){
            return this.select_item;
        }else{
            ii = ii;
        }
       return this.data[ii];
    },
    show:function(){
        this.disabled = false;
        this.containner.style.visibility = "visible";
    },
    hidden:function(){
        this.disabled = true;
        this.containner.style.visibility = "hidden";
    },
    //焦点获取逻辑 这里很乱
    itemGetFocus: function(i){

        var lastItem = this.select_item;
        var ii = Number(i);
        if( ii == ii){

            if(typeof this.data[ii] == "undefined"){
                return;
            }

            if(!this.select_item.dom && !(this.select_item instanceof FocusTables && item.data)){
                this.select_item.dom = $("leadingtv_"+this.select_item.index+"_"+this.name);
            }
            this.select_item = this.data[ii];
            this.index = ii;
        }else{
            ii = Number(this.index);
        }

        if(this.data&&this.data.length>0){
            if(!this.select_item.dom && !(this.select_item instanceof FocusTables)){
                this.select_item.dom = $("leadingtv_"+this.select_item.index+"_"+this.name);
            }
            if(!lastItem.dom && !(lastItem instanceof FocusTables)){
                lastItem.dom = $("leadingtv_"+lastItem.index+"_"+this.name);
            }
            this.focusChange(this.select_item,lastItem);
        }
        if(this.select_item&&typeof this.select_item.data != "undefined" && this.select_item.data.length != 0){
            this.itemLoseFocus();
            this.select_item.itemGetFocus();
        }
        return this.select_item;
    },
    itemLoseFocus: function(){

        if(this.select_item&&typeof this.select_item.data != "undefined" && this.select_item.data.length != 0){
            this.select_item.itemLoseFocus();
        }
        if(this.select_item){
            if(!this.select_item.dom &&!(this.select_item instanceof FocusTables)){
                this.select_item.dom = $("leadingtv_"+this.select_item.index+"_"+this.name);
            }
            this.itemFocusOut(this.select_item);
        }

    },
    itemFocusOn : function() {
        console.log("action","itemFocusOn")
    },
    itemFocusOut : function(item) {
        console.log("action","itemFocusOut")
    },
    focusChange:function(item,last_item){

        if(last_item){
            this.itemFocusOut(last_item);
        }

        this.itemFocusOn(item);
    },
    doSelect : function(ii) {

        if(typeof ii == "undefined"){
            var last_item = this.getSelectItem(this.select_index);
            this.setSelectIndex(this.select_item.index);
            this.enter(this.select_item,last_item);
        }else{
            var i = parseInt(ii);
            if(i == i){
                this.setSelectItem(ii);

                this.setSelectIndex(ii);
                this.enter(this.select_item);
            }

        }

    },
    overSize: function(_derection,_item){
        switch (_derection) {
            case 'right':
                this.overRight(this.select_item);
                break;
            case 'left':
                this.overLeft(this.select_item);
                break;
            case 'up':
                this.overTop(this.select_item);
                break;
            case 'down':
                this.overBottom(this.select_item);
                break;
            default:
                console.error("derection error",_derection);
                return false;
        }
    },
    overTop: function(_item){
        console.log("focus action","overTop");
    },
    overLeft:function(_item){
        console.log("focus action","overLeft");
    },
    overRight:function(_item){
        console.log("focus action","overRight");
    },
    overBottom:function(_item){
        console.log("focus action","overBottom");
    },
    areaItemFocusOn:function(item){

    },
    areaItemFocusOut:function(item){

    },
    doBack: function () {
        //默认返回 去当前的名字  比如 index.html
        var page_name = window.location.href.split("?")[0].split("/").pop();
        var backUrl = pageStorePop();

        if(backUrl == ""||backUrl == "null"){

            window.history.back(-1);
        }
        window.location.href = backUrl;
    },
    playVideoStart:function(){

    },
    playVideoEnd: function () {

    },
    createMediaPlayer: function () {

    },
    navCheckSuccess: function () {

    },
    navCheckError: function () {

    }
};
FocusTables.prototype.constructor = FocusTables;
function Focus(opt) {
    var that = this;
    for (var i in opt){
        this[i] = opt[i];
    }
    if(typeof this.containner == "undefined"){
        var containner = document.createElement("div");
        containner.style.position="absolute";
        containner.style.left = this.left||0;
        containner.style.top = this.top||0;
        containner.style.width = (this.width||1280) +"px";
        containner.style.height = (this.height||720) + "px";
        // containner.id = this.name+"-containner";
        // containner.name = this.name;
        this.containner = containner;
        document.body.appendChild(this.containner);
    }
    this.init();
}
var focus_id = 0;
Focus.prototype = {
    padding_top:10,
    padding_left:10,
    spacing_top:10,
    spacing_left:10,
    focus_id:"",
    margin_top:0,
    margin_left:0,
    focus_padding_top:10,
    focus_padding_left:10,
    td:20,
    zIndex:10,
    focusFolder:"images/focus",
    init:function(){

        if(typeof this.containner == "object" && this.containner != null ){

            if(typeof this.dom == "undefined" ||　!this.dom){

                var dom = document.createElement("div");
                domStyle({
                    "left":0,
                    "top":0,
                    "width":0,
                    "height":0

                },dom);
                dom.id = "page_focus_"+focus_id;
                dom.style.position = "absolute";
                dom.style.zIndex = 10;
                dom.style.display = "none";
                //dom.id = this.name;

            }
            dom.innerHTML = this.html().join("");
            this.containner.appendChild(dom);
            this.dom = dom;
            console.log(dom)
            focus_id++
        }
    },
    // focus:str
    defaultFocusChange:function (item,left,top) {
        if(typeof item == "undefined"){
            return;
        }
        var dom = this.dom
        var left =  left || 0;
        var top = top || 0;

        dom.style.display = "none";
        dom.style.width = item.width + this.padding_left * 3 +"px";
        dom.style.height = item.height + this.padding_top * 3  +"px";

        var spacing_left = this.spacing_left?this.spacing_left:this.padding_left;
        var spacing_top = this.spacing_top?this.spacing_top:this.padding_top;
        this.domPosMove(dom,item.left+left - spacing_left*1.5,item.top+top - spacing_top*1.5);
        dom.style.display = "block";
        return;
    },
    bigFocusChange:function (item, last_item){
        var dom = this.dom;
        this.is_big = true;
        var p_l = this.focus_padding_top||0;
        var p_t = this.focus_padding_left||0;
        dom.style.display = "none";

        dom.style.width = item.width + this.padding_left * 3 + p_l  +"px";
        dom.style.height = item.height + this.padding_top * 3 + p_t +"px";
        var spacing_left = this.spacing_left?this.spacing_left:this.padding_left;
        var spacing_top = this.spacing_top?this.spacing_top:this.padding_top;
        this.domPosMove(dom,item.left - spacing_left*1.5 - p_l/2,item.top - spacing_top*1.5-p_t/2);

        if(last_item&&last_item.dom){
            domStyle({
                width:last_item.width,
                height:last_item.height,
                left:last_item.left,
                top:last_item.top,
                zIndex:0

            },last_item.dom)
        }
        if(item&&item.dom){
            domStyle({
                width:(item.width + p_l),
                height:(item.height + p_t),
                left:(item.left - p_l/2),
                top:(item.top - p_t/2),
                zIndex:10
            },item.dom);
        }

        dom.style.display = "block";

    },
    domPosMove:function (dom,left,top) {

        var left = left ||　0;
        var top = top ||　0;
        dom.style.left = left + "px";
        dom.style.top = top + "px";
    },
    html:function () {
        return [
            "    <table width=\"100%\" height=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">",
            "        <tr>",
            "            <td width=\"",this.td,"\" height=\"",this.td,"\" style=\"background:url(",this.focusFolder,"/focus_lt.png); background-repeat:no-repeat;\"></td>",
            "            <td style=\"background:url(",this.focusFolder,"/focus_t.png);background-repeat:repeat-x;\"></td>",
            "            <td width=\"",this.td,"\" style=\"background:url(",this.focusFolder,"/focus_rt.png);background-repeat:no-repeat;\"></td>",
            "        </tr>",
            "        <tr>",
            "            <td style=\"background:url(",this.focusFolder,"/focus_l.png);background-repeat:repeat-y;\"></td>",
            "            <td style=\"\">&nbsp</td>",
            "            <td style=\"background:url(",this.focusFolder,"/focus_r.png);background-repeat:repeat-y;\"></td>",
            "        </tr>",
            "        <tr>",
            "            <td height=\"",this.td,"\" style=\"background:url(",this.focusFolder,"/focus_lb.png);background-repeat:no-repeat;\"></td>",
            "            <td style=\"background:url(",this.focusFolder,"/focus_b.png);background-repeat:repeat-x;\"></td>",
            "            <td  style=\"background:url(",this.focusFolder,"/focus_rb.png);background-repeat:no-repeat;\"></td>",
            "        </tr>",
            "    </table>",
            ]
    },
    show:function () {
        if(typeof this.dom != "undefined" && this.dom){
            this.dom.style.display = "block";
        }
    },
    hidden:function () {
        if(typeof this.dom != "undefined" && this.dom){
            this.dom.style.display = "none";
        }
    },
    setMarginTop:function (top) {
        this.margin_top = top;
    },
    setMarginLeft:function (left) {
        this.margin_left = left;
    }


};


/**
 *
 * @param array
 * @param menuTemplate //菜单参数
 * @param listParams //列表参数
 * @return {Array}
 */
function produceTemplateArr(array,menuTemplate,listParams) {
    var row = 0;
    var col = 0;
    var padding_left = 0;
    var padding_top = 0;
    var sp_t = 0;
    var sp_l = 0;
    if(listParams){
        row = parseInt(listParams['row']);
        col = parseInt(listParams['col']);
        padding_left = parseInt(listParams['padding_left']);
        padding_top = parseInt(listParams['padding_top']);
        sp_l = parseInt(listParams['space_left']);
        sp_t = parseInt(listParams['space_top']);
        row = row === row?row:0;
        col = col === col?col:0;
        padding_left = padding_left === padding_left?padding_left:0;
        padding_top = padding_top === padding_top?padding_top:0;
        sp_l = sp_l === sp_l?sp_l:0;
        sp_t = sp_t === sp_t?sp_t:0;

    }
    // var width = Number(width);
    // var height = Number(height);
    // var spaceing_left = Number(spaceing_left);
    // var spaceing_top = Number(spaceing_top);
    if(typeof array == "undefined"||array.length == 0  ){
        return array;
    }

    var listArr = [];
    var  menuTemplateLen = menuTemplate?menuTemplate.length:0;
    var len = row * col || menuTemplateLen;

    for (var i = 0;i<len;i++){
        var obj = null;

        if(listParams){
            obj = {
                left:i%col*(listParams['width']+sp_l) + padding_left,
                top:parseInt(i/col)*(listParams['height']+sp_t) + padding_top,
                width:listParams['width'],
                height:listParams['height']
            };
        }else if(menuTemplate){
            obj = menuTemplate[i];
        }

        obj["bottom"] = obj["bottom"]||obj["top"]+obj['height'];
        obj["right"] = obj["right"]||obj["left"]+obj['width'];
        obj["index"] = obj["index"]||i;

        if(typeof array[i] != "undefined" && i<array.length ){
            //这个是把多出来的属性赋值给新的对象
            for (var p in array[i]){
                obj[p] = array[i][p];
            }
            listArr.push(obj);
        }
    }
    if(listArr.length == 0){
        for(var i=0;i<array.length;i++){
            array[i]["bottom"] =  array[i]["bottom"]|| array[i]["top"]+ array[i]['height'];
            array[i]["right"] =  array[i]["right"]|| array[i]["left"]+ array[i]['width'];
            array[i]["index"] =  array[i]["index"]||i;
        }
        return array;
    }
    return listArr;
}


/**
 * 改变dom的style
 * @param style
 * @param dom
 */
function domStyle(style,dom) {
    //检查是否为dom
    if(typeof dom !== "object"|| dom.nodeType !== 1 || typeof dom.nodeName !== 'string'){
        return
    }
    var stylePertotype = ["left","top","right","bottom","width","height"];

    for (var i in style){
        if(stylePertotype.indexOf(i)!=-1 &&(style[i]+"").indexOf("px") == -1  ){
            dom["style"][i] = style[i] + "px";
        }else{
            dom["style"][i] = style[i];
        }

    }
    return true;
}

/**
 * 在某个方向focus2是否比focus1更好 更适合当总统:)
 * @param _derection
 * @param focus1
 * @param focus2
 */
function isBetterCandidate(_derection,focus1,focus2,selectFocus) {

    if(focus2 == selectFocus){
        return false;
    }

    // if(typeof focus1 != "object" || focus1 == null  ){
    //     return true;
    // }

    // if(typeof focus2 != "object" || focus1 == null){
    //     return false;
    // }


    //2在方向上1也在方向上



    //先判断在主轴方向是否重合
    var isCoincideInBeam1 = isCoincideInBeam(_derection,focus1,selectFocus);
    var isCoincideInBeam2 = isCoincideInBeam(_derection,focus2,selectFocus);

    if(!isCoincideInBeam2){
        return false;
    }
    // //1重合2不重合
    // if(isCoincideInBeam1 && !isCoincideInBeam2){
    //
    //     //console.log("1重合2不重合："+focus1["title"]+","+focus2["title"]);
    //     return false;
    // }
    //2重合1不重合
    if(isCoincideInBeam2 && !isCoincideInBeam1){
        return true;
    }

    //都不重合
    // if(!isCoincideInBeam2 && !isCoincideInBeam1){
    //     return false;
    // }
    //获取主轴距离
    var distance1 = getDistanceToCloseEdge(_derection,focus1,selectFocus);
    var distance2 = getDistanceToCloseEdge(_derection,focus2,selectFocus);
    //都不重合 或者 都重合 判断主轴方向距离对比
    //距离1比2大则说明2比1合适
    if( distance1 > distance2){
        return true;
    }



    //等于的时候 判断中线与副轴距离
    if(distance1 == distance2){

        var counterDistance1 = getCounterDistance(_derection,focus1,selectFocus);
        var counterDistance2 = getCounterDistance(_derection,focus2,selectFocus);


        if(counterDistance1 > counterDistance2){
            return true;
        }
    }
    //小于 判断副轴方向  只有当最远边距离>最近边距离 才是更合适

    return false;

}

/**
 * focus1是否在focus2某个方向上  以该方向的底边和中线对比中线
 * @param _derection
 * @param focus1 当前候选人
 * @param focus2 当前选中
 */
function isInBeamDerection(_derection, focus1, focus2) {
    switch (_derection) {
        case 'right':
            return (focus1["left"]+focus1["right"])/2 >= focus2['right'];
            break;
        case 'left':
            return (focus1["left"]+focus1["right"])/2<=focus2['left'];
            break;
        case 'up':
            return (focus1["top"]+focus1["bottom"])/2<=focus2['top'];
            break;
        case 'down':
            return (focus1["top"]+focus1["bottom"])/2>=focus2['bottom'];
            break;
        default:
            console.error("derection error",_derection);
            return false;
    }


}

/**
 * 判断focus1在某个方向上是否与focus2重合
 * @param _derection
 * @param focus1
 * @param focus2
 * @return boolean
 */
function isCoincideInBeam(_derection,focus1,focus2) {

    //focus如果是null  那么直接返回不重合
    if(typeof focus1 != "object"||focus1==null || typeof focus2 != "object" ){
        return false;
    }
    switch (_derection) {
        case 'right':
        case 'left':
            //下边在2中间
            if(focus1["bottom"]>=focus2["top"]&&focus1["bottom"]<=focus2["bottom"]){
                return true;
            }
            //上边在2 中间
            if(focus1["top"]>=focus2["top"]&&focus1["top"]<=focus2["bottom"]){
                return true;
            }

            //2在1的上下边中间
            if(focus1["top"]<=focus2["top"]&&focus1["bottom"]>=focus2["bottom"]){
                return true;
            }
            return false;
           break;
       case 'up':
       case 'down':
           //下边在2中间
           if(focus1["right"]>=focus2["left"]&&focus1["right"]<=focus2["right"]){
               return true;
           }
           //上边在2 中间
           if(focus1["left"]>=focus2["left"]&&focus1["left"]<=focus2["right"]){
               return true;
           }

           //2在1的上下边中间
           if(focus1["left"]<=focus2["left"]&&focus1["right"]>=focus2["right"]){
               return true;
           }
           break;
        default:
            console.error("derection error",_derection);
            return false;
   }
}

/**
 * 获取focus1距离foucs2某个方向上近边的距离  比如向上就获取 focus1 的 top 距离 focus2的bottom 的距离
 * @param _derection
 * @param focus1
 * @param focus2
 * @return distance (Number)
 */
function getDistanceToCloseEdge(_derection,focus1,focus2) {

    switch (_derection) {
        case 'right':
            return Math.abs(focus1["left"] - focus2["right"]);
            break
        case 'left':
            return Math.abs(focus1["right"] - focus2["left"]);
            break;
        case 'up':
            return Math.abs(focus1["bottom"] - focus2["top"]);
            break;
        case 'down':
            return Math.abs(focus1["top"] - focus2["bottom"]);
            break
        default:
            console.error("derection error",_derection);
    }
}

/**
 * 获取副轴距离的俩倍
 * @param _derection
 * @param focus1
 * @param focus2
 * @return {number}
 */
function getCounterDistance(_derection,focus1,focus2) {

    if(typeof focus1 != "object" || typeof focus2 != "object" ){

        return 0;
    }
    switch (_derection) {
        case 'up':
        case 'down':
            return Math.abs((focus2["left"]+focus2["right"])/2 - (focus1["right"] + focus1['left'])/2);
            break
        case 'left':
        case 'right':
            return Math.abs((focus2["top"]+focus2["bottom"])/2 - (focus1["top"] + focus1['bottom'])/2);
            break;
    }
    console.error("derection error",_derection);
}

/**
 * 生产列表的Array  因为请求到的内容是没有left,top,width,height 这几个参数的 所以需要负责
 * @param row
 * @param col
 * @param width
 * @param height
 * @param spaceing_left
 * @param spaceing_top
 * @param padding_left
 * @param padding_top
 */
function produceListArr(row,col,width,height,array,spaceing_left,spaceing_top,padding_left,padding_top) {
    var row = Number(row);
    var col = Number(col);
    // var width = Number(width);
    // var height = Number(height);
    // var spaceing_left = Number(spaceing_left);
    // var spaceing_top = Number(spaceing_top);
    if(typeof array == "undefined"||array.length == 0  ){
        return [];
    }
    var sp_l = typeof spaceing_left == "undefined" ? 0:spaceing_left  ,sp_t = typeof spaceing_top == "undefined"?0:spaceing_top;

    var padding_left = parseInt(padding_left);
    padding_left = padding_left == padding_left?padding_left:0;
    var padding_top = parseInt(padding_top);
    padding_top = padding_top == padding_top?padding_top:0;
    var listArr = [];
    for (var i = 0,len = row * col;i<len;i++){
        var obj = {
            left:i%col*(width+sp_l) + padding_left,
            top:parseInt(i/col)*(height+sp_t) + padding_top,
            width:width,
            height:height
        };

        if(typeof array[i] != "undefined" && i<array.length ){
            //这个是把多出来的属性赋值给新的对象
            for (var p in array[i]){
                obj[p] = array[i][p];
            }
            listArr.push(obj);
        }
    }
    return listArr;
}




/**
 * 设置缓存
 * @param _key
 * @param _value
 */
function setGlobalVar(_key, _value) {
    if("undefined" != typeof(iPanel)) {
        iPanel.setGlobalVar(_key, _value + "");
    }else if(localStorage){
        localStorage.setItem(_key,_value);
    } else {
        setCookie(_key, _value + "");
    }
}



/**
 * 获取缓存
 * @param _key
 * @return {*|string}
 */
function getGlobalVar(_key) {
    if("undefined" != typeof(iPanel)) {
        return iPanel.getGlobalVar(_key) || "";
    }else if(localStorage){
        return localStorage.getItem(_key);
    } else {
        return getCookie(_key);
    }
}

function pageRedirectTo(url,backParams) {

    var backUrl = window.location.href.split('?')[0];

    if(backParams && backParams == "object"){
        for (var i in backParams){
            if(backParams.hasOwnProperty(i)){
                backUrl+="&"+i+"="+backParams[i];
            }
        }
    }
    pageStorePush(backUrl,backParams);
    window.location.href = url ;
}


function pageStorePush(backUrl,params) {

    if(backUrl.indexOf("?")!=-1){
        if(params && params == "object"){
            for (var i in params){
                if(params.hasOwnProperty(i)){
                    backUrl+="&"+i+"="+params[i];
                }
            }
        }
    }else {
        if(params && typeof params == "object"){
            backUrl+="?";
            for (var i in params){
                if(params.hasOwnProperty(i)){
                    backUrl+=i+"="+params[i]+"&";
                }
            }
        }
    }
    var url_back_store = getGlobalVar("url_back_store");
    var  storeArr = [];
    if(url_back_store){
        storeArr = url_back_store.split(",");
    }

    storeArr.push(backUrl);

    setGlobalVar("url_back_store",storeArr.join(","));
    return storeArr;
}


function pageStorePop() {
    var url_back_store = getGlobalVar("url_back_store");
    var storeArr = url_back_store.split(",");
    var backUrl = storeArr.pop();

    setGlobalVar("url_back_store",storeArr.join(","));
    return backUrl;
}

function getPageStore(backUrl) {
    var url_back_store = getGlobalVar("url_back_store");
    var storeArr = url_back_store.split(",");
    return storeArr;
}

/**
 * 设置页面返回地址
 * @param pagename
 * @param backurl
 */
function setPageBackUrl(href,backurl,params){
    if(backurl.indexOf("?")!=-1){

        if(params && params == "object"){
            for (var i in params){
                if(params.hasOwnProperty(i)){
                    backurl+="&"+i+"="+params[i];
                }
            }
        }
    }else {

        if(params && typeof params == "object"){
            backurl+="?";
            for (var i in params){
                if(params.hasOwnProperty(i)){
                    backurl+=i+"="+params[i]+"&";
                }
            }
        }
    }

    var pagename = getPageName(href);

    setGlobalVar(pagename+"_backUrl",backurl);
}

/**
 * 获取页面返回路径
 * @param href
 * @return {*|string}
 */
function getPageBackUrl(href) {
    if(href == ""){
        return null;
    }
    var pagename = getPageName(href);
    return getGlobalVar(pagename+"_backUrl");
}

/**
 * 获取页面名字
 * @param href
 * @return {string | *}
 */
function getPageName(href) {

    var page_name = href.split("?")[0].split("/").pop();

    if (page_name == ""){
        page_name = href;
    }
    return page_name;
}


/**
 * 获取按键对应按钮
 * @param _event
 * @return {string|number|string}
 */
// JavaScript Document
function keyEvent(_event){
    var keycode = _event.keyCode | _event.which;
    var code = "";
    switch (keycode) {
        case 1:
        case 38: //other browsers
        case 65362: //上
        case 87:
            code = "KEY_UP";
            break;
        case 2:
        case 40: //other browsers
        case 65364: //下
        case 83:
            code = "KEY_DOWN";
            break;
        case 3:
        case 37: //other browsers
        case 65361: //左
        case 65:
            code = "KEY_LEFT";
            break;
        case 4:
        case 39: //other browsers
        case 65363: //右
        case 68:
            code = "KEY_RIGHT";
            break;
        case 13:
        case 65293: //确定
            code = "KEY_SELECT";
            break;
        //case 340:
        case 640:
        case 283:
        case 8: //other browsers
        //case 27: //谷歌浏览器返回键返回页面问题，用ESC键暂代
        case 65367: //返回
            code = "KEY_BACK";
            break;
        case 27:
        case 339:
        case 340:
            code = "KEY_EXIT";
            break;
        case 372:
        case 25: //向前翻页
        case 33:
        case 306:
            code = "KEY_PAGE_UP";
            break;
        case 373:
        case 26: //向后翻页
        case 34:
        case 307:
            code = "KEY_PAGE_DOWN";
            break;
        case 513: //right [Ctrl]
        case 65360: //菜单
        case 72:
            code = "KEY_MENU";
            break;
        case 595: //[+]
        case 63561: //音量加
        case 61:
            code = "KEY_VOLUME_UP";
            break;
        case 596: //[-]
        case 63562: //音量减
        case 45:
            code = "KEY_VOLUME_DOWN";
            break;
        case 597: //[.]
        case 63563: //静音
        case 67:
            code = "KEY_VOLUME_MUTE";
            break;
        case 32:
            code = "KEY_F1";
            break;
        case 33:
            code = "KEY_F2";
            break;
        case 34:
            code = "KEY_F3";
            break;
        case 35:
            code = "KEY_F4";
            break;
        case 49:
            code = "KEY_NUMBER1";
            break;
        case 50:
            code = "KEY_NUMBER2";
            break;
        case 51:
            code = "KEY_NUMBER3";
            break;
        case 52:
            code = "KEY_NUMBER4";
            break;
        case 53:
            code = "KEY_NUMBER5";
            break;
        case 54:
            code = "KEY_NUMBER6";
            break;
        case 55:
            code = "KEY_NUMBER7";
            break;
        case 56:
            code = "KEY_NUMBER8";
            break;
        case 57:
            code = "KEY_NUMBER9";
            break;
        case 48:
            code = "KEY_NUMBER0";
            break;
        case 65307:
            code = "KEY_TRACK";
            break;
        case 36: // 喜爱
        case 76:
            code = "KEY_FAV";
            break;
        case 72: // 回看
            code = "KEY_PALYBACK";
            break;
        case 320://red
        case 832:
            code = "KEY_RED";
            break;
        case 321://green
        case 833:
            code = "KEY_GREEN";
            break;
        case 322://yellow
        case 834:
            code = "KEY_YELLOW";
            break;
        case 323: //蓝键
        case 835:
            code = "KEY_BLUE";
            break;
        case 11001:
        case 10901:
            code = "PLAY_END";
            break;
        case 5210:
        case 5209:
            code = "IPANEL_PLAY_?";
            break;
        case 5226:
            code = "IP_PLAY_5226";
            break;
        default:
            code = keycode;
            break;

    }
    return code;
};

/**
 * 写cookie
 * @param name
 * @param value
 */
function setCookie(name,value) {
    var exp = new Date();
    exp.setTime(exp.getTime() +24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";path=/;expires=" + exp.toGMTString();
}

/**
 * //读取cookies
 * @param name
 * @return {*}
 */
function getCookie(name) {
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg)) return unescape(arr[2]);
    else return null;
}

/**
 * 删除cookies
 * @param name
 */
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";path=/;expires="+exp.toGMTString();
}

/**
 * ajax请求函数
 * @param _optionsObj
 * @param _cfFlag
 * @param _time_out
 */
function ajax(_optionsObj, _cfFlag, _time_out) {

    var time_out = _time_out || new Date().getTime();
    var optionsObj = {
        // HTTP 请求类型
        type:        _optionsObj.type || "GET",
        // 请求的文件类型
        dataType:    _optionsObj.dataType,
        // 请求的URL
        url:        _optionsObj.url || "",
        //请求方式，true异步请求，false同步请求
        requestType: _optionsObj.requestType === false ? false:true,
        // 请求的超时时间
        time_out:    _optionsObj.time_out || 10000,
        // 请求成功.失败或完成(无论成功失败都会调用)时执行的函数
        onComplete: _optionsObj.onComplete || function(){},
        onError:    _optionsObj.onError || function(){},
        onSuccess:    _optionsObj.onSuccess || function(){},
        // 服务器端默认返回的数据类型
        data:        _optionsObj.data || "",
        post:        _optionsObj.post || ""
    };
    var cfFlag = _cfFlag || true;

    var ajaxZXFlag = true;
    // 强制关闭函数
    var timeOutRD = setTimeout(function(){
        clearTimeout(timeOutRD);
        ajaxZXFlag = false;
        if(!cfFlag) {
            ajax(optionsObj, true, time_out);
        } else {
            optionsObj.onError();

            //var time_in = new Date().getTime();
            //var time_c = time_in - time_out;
            //$("msgvalue").innerHTML = "time : " + time_c + " timeOutRD readyState : " + xml.readyState + " and xml.status : " + xml.status;
        }
    }, optionsObj.time_out);

    var xml = createXHR();

    xml.onreadystatechange = function() {
        if(xml.readyState == 4 && ajaxZXFlag){
            // 检查是否请求成功
            clearTimeout(timeOutRD);
            if(httpSuccess(xml) && ajaxZXFlag){
                // 以服务器返回的数据作为参数执行成功回调函数
                optionsObj.onSuccess(httpData(xml, optionsObj.dataType ));
            }else{
                optionsObj.onError();
                //var time_in = new Date().getTime();
                //var time_c = time_in - time_out;
                //$("msgvalue").innerHTML = "time : " + time_c + " timeOutRD readyState : " + xml.readyState + " and xml.status : " + xml.status;
            }

            // 调用完成后的回调函数
            optionsObj.onComplete(xml);
            // 避免内存泄露,清理文档
            xml = null;
        }
    }
    var url;
    if(optionsObj.url.indexOf("?") > -1) {
        url = optionsObj.url + "&timestamp=" + new Date().getTime();
    } else {
        url = optionsObj.url + "?timestamp=" + new Date().getTime();
    }
    xml.open(optionsObj.type, url, optionsObj.requestType);
    if("GET" == optionsObj.type){
        xml.send(null);
    }else{
        xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xml.send(optionsObj.post);
    }
}
function createXHR() {
    if(typeof XMLHttpRequest != "undefined") {
        createXHR = function() {
            return new XMLHttpRequest();
        };
    } else if(typeof ActiveXObject != "undefined") {
        createXHR = function() {
            if(typeof arguments.callee.activeXString != "string") {
                var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"];
                for(var i = 0, len = versions.length; i < len; i++) {
                    try {
                        var xhr = new ActiveXObject(versions[i]);
                        arguments.callee.activeXString = versions[i];
                        return xhr;
                    } catch(ex) {
                        //跳过
                        if(len - 1 == i) {
                            throw new Error("there is no xmlhttprequest object available");
                        }
                    }
                }
            } else {
                return new ActiveXObject(arguments.callee.activeXString);
            }
        };
    } else {
        createXHR = function() {
            throw new Error("there is no xmlhttprequest object available");
        };
    }
    return createXHR();
}

// 判断HTTP响应是否成功
function httpSuccess(r){
    var flag = false;
    try {
        if((r.status >= 200 && r.status <= 300) || r.status == 304) {
            // 如果得不到服务器状态,且我们正在请求本地文件,则认为成功
            flag = true;
        } else if(!r.status && location.protocol == "file:") {
            // 所有200-300之间的状态码 表示成功
            flag = true;
        } else if(navigator.userAgent.indexOf('Safari') >= 0 && typeof r.status == "undefined") {
            // Safari在文档未修改的时候返回空状态
            flag = true;
        } else {
            flag = false;
        }
    }catch(e){
        flag = false;
    } finally {
        return flag;
    }

    // 若检查状态失败,则假定请求是失败的
}

// 从HTTP响应中解析正确数据
function httpData(r, type){
    // 获取content-type的头部
    var ct = r.getResponseHeader("content-type");
    // 如果没有提供默认类型, 判断服务器返回的是否是XML形式
    var data = !type && ct && ct.indexOf('xml') >= 0;

    // 如果是XML则获得XML对象 否则返回文本内容
    data = type == "xml" || data ? r.responseXML : r.responseText;

    // 如果指定类型是script,则以javascript形式执行返回文本
    if(type == "script"){
        eval.call(window, data);
    }

    // 返回响应数据
    return data;
}




// 数据串行化 支持两种不同的对象
// - 表单输入元素的数组
// - 键/ 值 对应的散列表
// - 返回串行化后的字符串 形式: name=john& password=test

function serialize(a) {
    // 串行化结果存放
    var s = [];
    // 如果是数组形式 [{name: XX, value: XX}, {name: XX, value: XX}]
    if(a.constructor == Array){
        // 串行化表单元素
        for(var i = 0; i < a.length; i++){
            s.push(a[i].name + "=" + encodeURIComponent( a[i].value ));
        }
        // 假定是键/值对象
    }else{
        for( var j in a ){
            s.push( j + "=" + encodeURIComponent( a[j] ));
        }
    }
    // 返回串行化结果
    return s.join("&");
}

//url参数工具
var Q = Query = {
    getFromURL: function(url,parameter){
        var index = url.indexOf("?");
        if (index != -1) {
            var parameterString = url.substr(index + 1);
            var reg = new RegExp("(^|&)" + parameter + "=([^&]*)(&|$)", "i");
            var r = parameterString.match(reg);
            if (r != null){
                return r[2];
            }
        }
        return null;
    },
    get: function(parameter) {
        if (typeof (parameter) == "undefined" || parameter == "") {
            return null;
        }
        var url = window.location.href;
        var index = url.indexOf("?");
        if (index != -1) {
            var parameterString = url.substr(index + 1);
            var reg = new RegExp("(^|&)" + parameter + "=([^&]*)(&|$)", "i");
            var r = parameterString.match(reg);
            if (r != null){
                return r[2];
            }
        }
        return null;
    },
    getInt:function(parameter,defaultValue){
        var value = parseInt(this.get(parameter));
        return isNaN(value) ? (typeof(defaultValue) == "undefined" ? 0 : defaultValue) : value;
    },
    getDecoded:function(parameter){
        return this.decode(this.get(parameter));
    },
    decode:function(srcStr){
        if(typeof(srcStr) == "undefined"){return null;}
        return decodeURIComponent(srcStr);
    },
    encode:function(srcStr){
        if(typeof(srcStr) == "undefined"){return null;}
        return encodeURIComponent(srcStr);
    },
    getSymbol:function(url){
        return url.indexOf("?") == -1 ? "?" : "&";
    },
    joinURL:function(url,queryString){
        return url + this.getSymbol(url) + queryString;
    },
    createQueryString:function(obj){
        var a = [];
        for(var p in obj){
            if(typeof(obj[p]) == "function" || obj[p] == null || typeof(obj[p])=="undefined") continue;
            a.push(p + "=" + obj[p]);
        }
        return a.join("&");
    }
};
window.box_log_top = 100;
function box_log(log,container) {

    var container = container
    if(container == null || container == undefined){
        container = $("bg");
    }
    if(container == null){
        return;
    }
    var log_div = document.createElement("div");
    log_div.innerHTML = log;
    log_div.style.position =  "absolute";
    log_div.style.left =  "100px";
    log_div.style.top =  window.box_log_top+"px";
    log_div.style.color =  "red";
    log_div.style.zIndex = 10000;
    window.box_log_top+=50;
    container.appendChild(log_div);
}

function each(array, callback, reversed) {
    var length = array.length;
    if (length) {
        if (reversed) {
            for (var i = length - 1; i >= 0; i--) {
                if (callback(array[i], i) === FALSE) {
                    break;
                }
            }
        }
        else {
            for (var i = 0; i < length; i++) {
                if (callback(array[i], i) === FALSE) {
                    break;
                }
            }
        }
    }
}


